# ODBC Direct Connection Test Script (with extra params)
$driver = "DM8 ODBC DRIVER"  # 必须是ODBC管理器里显示的驱动名称
$server = "<your_host>:<your_port>"
$uid = "<your_uid>"
$pwd = "<your_pwd>"
# $database = ""  # 如有需要可加

# 补充常见参数
$connStr = "Driver={$driver};Server=$server;UID=$uid;PWD=$pwd;ServerType=8;Protocol=TCP;"

# 如果需要指定数据库名，取消下一行注释
# $connStr += "Database=$database;"

Write-Host "Testing ODBC Direct Connection..."
Write-Host "Connection String: $connStr"

try {
    $conn = New-Object -ComObject ADODB.Connection
    $conn.ConnectionString = $connStr
    $conn.Open()
    Write-Host "SUCCESS: ODBC Connection Established!"

    $sql = "SELECT * FROM b01 FETCH FIRST 10 ROWS ONLY"
    $rs = $conn.Execute($sql)

    $fieldCount = $rs.Fields.Count
    $fieldNames = @()
    for ($i = 0; $i -lt $fieldCount; $i++) {
        $fieldNames += $rs.Fields.Item($i).Name
    }

    # 输出到文件，保证UTF-8编码
    $outputFile = "output.txt"
    "字段名: " + ($fieldNames -join ", ") | Out-File -FilePath $outputFile -Encoding utf8 -Append

    while (!$rs.EOF) {
        $row = @()
        for ($i = 0; $i -lt $fieldCount; $i++) {
            $row += $rs.Fields.Item($i).Value
        }
        "数据: " + ($row -join ", ") | Out-File -FilePath $outputFile -Encoding utf8 -Append
        $rs.MoveNext()
    }

    $conn.Close()
    Write-Host "Connection Closed"
    Write-Host "请用支持UTF-8的编辑器（如VSCode、Notepad++）打开 output.txt 查看字段名和数据"
} catch {
    Write-Host "ERROR: ODBC Connection Failed"
    Write-Host $_.Exception.Message
}

Write-Host "Test Complete" 